<template>
  <view class="uni-container">
    <uni-forms ref="form" :model="formData" validateTrigger="bind">
      <uni-forms-item name="category_id" label="分类" required>
        <uni-data-picker v-model="formData.category_id" collection="opendb-news-categories" field="name as text, _id as value"></uni-data-picker>
      </uni-forms-item>
      <uni-forms-item name="title" label="标题" required>
        <uni-easyinput placeholder="标题" v-model="formData.title" trim="both"></uni-easyinput>
      </uni-forms-item>
	  <uni-forms-item name="avatar" label="封面大图">
	    <uni-file-picker file-mediatype="image" return-type="object" v-model="formData.avatar"></uni-file-picker>
	  </uni-forms-item>
      <uni-forms-item name="content" label="图文内容" required>
        <uni-easyinput type="textarea" autoHeight placeholder="图文内容" v-model="formData.content" trim="right"></uni-easyinput>
		<view class="edit" style="height: 360px;">
			<sp-editor
			       :toolbar-config="{
			         excludeKeys: ['direction', 'date', 'lineHeight', 'letterSpacing', 'listCheck'],
			         iconSize: '18px'
			       }"
			       @init="initEditor"
			       @input="inputOver"
			       @upinImage="upinImage"
			       @overMax="overMax"
			       @addLink="addLink"
			       @exportHtml="exportHtml"
			     ></sp-editor>
		</view>
      </uni-forms-item>
      <uni-forms-item name="excerpt" label="图文摘录">
        <uni-easyinput placeholder="图文摘录" v-model="formData.excerpt" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="article_status" label="图文状态">
        <uni-data-checkbox v-model="formData.article_status" :localdata="formOptions.article_status_localdata"></uni-data-checkbox>
      </uni-forms-item>
   
      <uni-forms-item name="publish_date" label="发表时间">
        <uni-datetime-picker return-type="timestamp" v-model="formData.publish_date"></uni-datetime-picker>
      </uni-forms-item>
      <uni-forms-item name="last_modify_date" label="最后修改时间">
        <uni-datetime-picker return-type="timestamp" v-model="formData.last_modify_date"></uni-datetime-picker>
      </uni-forms-item>
  
      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
        <navigator open-type="navigateBack" style="margin-left: 15px;">
          <button class="uni-button" style="width: 100px;">返回</button>
        </navigator>
      </view>
    </uni-forms>
  </view>
</template>

<script>
  import { validator } from '../../js_sdk/validator/opendb-news-articles.js';

  const db = uniCloud.database();
  const dbCmd = db.command;
  const dbCollectionName = 'opendb-news-articles';

  function getValidator(fields) {
    let result = {}
    for (let key in validator) {
      if (fields.includes(key)) {
        result[key] = validator[key]
      }
    }
    return result
  }

  

  export default {
    data() {
      let formData = {
        "user_id": "",
        "category_id": "",
        "title": "",
        "content": "",
        "excerpt": "",
        "article_status": 0,
        "comment_status": null,
        "last_comment_user_id": "",
        "avatar": { url: ''},
        "publish_date": null,
        "last_modify_date": null,
        "mode": null
      }
      return {
		editorIns: null,
        formData,
        formOptions: {
          "article_status_localdata": [
            {
              "value": 0,
              "text": "草稿箱"
            },
            {
              "value": 1,
              "text": "已发布"
            }
          ],
          "comment_status_localdata": [
            {
              "value": 0,
              "text": "关闭"
            },
            {
              "value": 1,
              "text": "开放"
            }
          ]
        },
        rules: {
          ...getValidator(Object.keys(formData))
        }
      }
    },
    onLoad(e) {
      if (e.id) {
        const id = e.id
        this.formDataId = id
        this.getDetail(id)
      }
    },
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
    methods: {
      
      /**
       * 验证表单并提交
       */
      submit() {
        uni.showLoading({
          mask: true
        })
        this.$refs.form.validate().then((res) => {
          return this.submitForm(res)
        }).catch(() => {
        }).finally(() => {
          uni.hideLoading()
        })
      },

      /**
       * 提交表单
       */
      submitForm(value) {
        // 使用 clientDB 提交数据
        return db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
          uni.showToast({
            title: '修改成功'
          })
          this.getOpenerEventChannel().emit('refreshData')
          setTimeout(() => uni.navigateBack(), 500)
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        })
      },
	  /**
	   * 获取输入内容
	   * @param {Object} e {html,text} 内容的html文本，和text文本
	   */
	  inputOver(e) {
		// 可以在此处获取到编辑器已编辑的内容
		console.log('==== inputOver :', e)
			this.formData.content=e.html
	  },
	  /**
	   * 超出最大内容限制
	   * @param {Object} e {html,text} 内容的html文本，和text文本
	   */
	  overMax(e) {
		// 若设置了最大字数限制，可在此处触发超出限制的回调
		console.log('==== overMax :', e)
	  },
	  /**
	   * 编辑器就绪
	   * @param {Object} editor 编辑器实例，你可以自定义调用editor实例的方法
	   * @tutorial editor组件 https://uniapp.dcloud.net.cn/component/editor.html#editor-%E7%BB%84%E4%BB%B6
	   * @tutorial 相关api https://uniapp.dcloud.net.cn/api/media/editor-context.html
	   */
	  initEditor(editor) {
		this.editorIns = editor // 保存编辑器实例
	  },
	  preRender(html) {
		 setTimeout(() => {
				// 异步获取后端数据后，初始化编辑器内容
				this.editorIns.setContents({
				  html
				})
			  }, 1000)
	  },
	  /**
	   * 直接运行示例工程插入图片无法正常显示的看这里
	   * 因为插件默认采用云端存储图片的方式
	   * 以$emit('upinImage', tempFiles, this.editorCtx)的方式回调
	   * @param {Object} tempFiles
	   * @param {Object} editorCtx
	   */
	  upinImage(tempFiles, editorCtx) {
		/**
		 * 本地临时插入图片预览
		 * 注意：这里仅是示例本地图片预览，因为需要将图片先上传到云端，再将图片插入到编辑器中
		 * 正式开发时，还请将此处注释，并解开下面 使用 uniCloud.uploadFile 上传图片的示例方法 的注释
		 * @tutorial https://uniapp.dcloud.net.cn/api/media/editor-context.html#editorcontext-insertimage
		 */
			tempFiles.forEach(async (item) => {
				uni.showLoading({
				  title: '上传中请稍后',
				  mask: true
				})
				let upfile = await uniCloud.uploadFile({
				  filePath: item.path,
				  // 同名会导致报错 policy_does_not_allow_file_overwrite
				  // cloudPath可由 想要存储的文件夹/文件名 拼接，若不拼文件夹名则默认存储在cloudstorage文件夹中
				  cloudPath: `cloudstorage/${item.name}`,
				  cloudPathAsRealPath: true
				})
				editorCtx.insertImage({
				  src: upfile.fileID,
				  width: '80%', // 默认不建议铺满宽度100%，预留一点空隙以便用户编辑
				  success: function () {
					uni.hideLoading()
				  }
				})
			  })
  
	  },
	  /**
	   * 导出 - toolbar需要开启export工具
	   * @param {string} e 导出的html内容
	   */
	  exportHtml(e) {
		uni.navigateTo({
		  url: '/pages/out/out',
		  success(res) {
			// 传至导出页面解析即可
			res.eventChannel.emit('e-transmit-html', {
			  data: e
			})
		  }
		})
	  },
	  /**
	   * 添加超链接
	   * @param {Object} e { text: '链接描述', href: '链接地址' }
	   */
	  addLink(e) {
		console.log('==== addLink :', e)
	  },
      /**
       * 获取表单数据
       * @param {Object} id
       */
      getDetail(id) {
        uni.showLoading({
          mask: true
        })
        db.collection(dbCollectionName).doc(id).field("user_id,category_id,title,content,excerpt,article_status,comment_status,last_comment_user_id,avatar,publish_date,last_modify_date,mode").get().then((res) => {
          const data = res.result.data[0]
          if (data) {
            this.formData = data
            this.preRender(data.content)
          }
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        }).finally(() => {
          uni.hideLoading()
        })
      }
    }
  }
</script>
